package com.chance.cc.crawler.development.scripts.cnsf99;

import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerRecordContext;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.pipeline.result.CrawlerData;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.core.script.crawler.CrawlerCommonScript;
import com.chance.cc.crawler.core.selector.Selectable;
import com.chance.cc.crawler.core.tags.crawler.CrawlerResultTags;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerDataType.article;
import static com.chance.cc.crawler.development.scripts.allfeild.AICCommonField.*;

/**
 * @Author Zhao.Hhuan
 * @Date Create in 2020/11/24 13:44
 * @Description 养老网
 **/
public class Cnsf99CrawlerScript extends CrawlerCommonScript {

    private Logger log = LoggerFactory.getLogger(Cnsf99CrawlerScript.class);

    public static final String prefixUrl = "http://cnsf99.com";
    public static final String entranceUrl = "http://cnsf99.com/";//入口地址
    public static final String modelUrl = "http://cnsf99.com/(News|Nw)/index.html\\?id=\\d*|http://cnsf99.com/(News|Nw)/index\\?page=\\d*&id=\\d*";//模块地址
    public static final String articleUrl = "http://cnsf99.com/\\S*/index.html\\?id=\\d*&aid=\\d*|http://cnsf99.com/\\S*/index/id/\\d*/aid/\\d*";//文章地址

    /**
     * 脚本domain定义
     *
     * @return
     */
    @Override
    public String domain() {
        return "cnsf99";
    }

    /**
     * 进入脚本的正则列表
     */
    @Override
    public void initUrlRegulars() {
        addUrlRegular(entranceUrl);
        addUrlRegular(modelUrl);
        addUrlRegular(articleUrl);

    }

    /**
     * 是否执行脚本 ： 输入数据检查，合格的才进入脚本
     *
     * @param crawlerRequestRecord
     * @return
     */
    @Override
    public boolean crawlerCheck(CrawlerRequestRecord crawlerRequestRecord) {
        return true;
    }


    /**
     * 解析链接方法
     *
     * @param crawlerRequestRecord
     * @param httpPage
     * @return
     */
    @Override
    public List<CrawlerRequestRecord> parseLinks(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {
        List<CrawlerRequestRecord> parsedLinks = new ArrayList<CrawlerRequestRecord>();

        String requestUrl = httpPage.getRequest().getUrl();

        if (requestUrl.matches(entranceUrl)) {
            List<String> nodes = httpPage.getHtml().xpath("//div[@class=\"index_title\"]//@href").all();
            for (String itemUrl : nodes) {
                itemUrl = prefixUrl + itemUrl;
                if (itemUrl.matches(modelUrl)) {
                    CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                            .turnPageRequest(crawlerRequestRecord)
                            .httpUrl(itemUrl)
                            .recordKey(itemUrl)
                            .notFilterRecord()
                            .releaseTime(System.currentTimeMillis())
                            .build();

                    parsedLinks.add(itemRecord);
                }

            }
        } else if (requestUrl.matches(modelUrl)) {
            String nextPageUrl = StringEscapeUtils.unescapeHtml4(httpPage.getHtml().xpath("//a[@class=\"page-btn\"]/@href").get());
            if (StringUtils.isNotEmpty(nextPageUrl)) {
                nextPageUrl = prefixUrl + nextPageUrl;
                CrawlerRequestRecord turnPageRequest = CrawlerRequestRecord.builder()
                        .turnPageRequest(crawlerRequestRecord)
                        .recordKey(nextPageUrl)
                        .httpUrl(nextPageUrl)
                        .releaseTime(System.currentTimeMillis())
                        .build();
                parsedLinks.add(turnPageRequest);
            }

            List<Selectable> nodes = httpPage.getHtml().xpath("//div[@class=\"top_list\"]/div[@class=\"top_list_right\"]").nodes();
            for (Selectable node : nodes) {
                String itemUrl = StringEscapeUtils.unescapeHtml4(node.xpath("./div[@class=\"top_list_rtitle\"]/a/@href").get());
                if (StringUtils.isBlank(itemUrl)) {
                    continue;
                }
                itemUrl = itemUrl.matches(articleUrl) ? itemUrl : prefixUrl + itemUrl;

                String releaseTime = node.xpath(".//div[@class=\"top_list_rdate\"]/text()").get();
                if (StringUtils.isBlank(releaseTime)) {
                    continue;
                }

                try {
                    Long releaseTimeToLong = DateUtils.parseDate(releaseTime.trim().replaceAll("/n",""), "yyyy-MM-dd").getTime();

                    CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                            .itemPageRequest(crawlerRequestRecord)
                            .recordKey(itemUrl)
                            .httpUrl(itemUrl)
                            .releaseTime(releaseTimeToLong)
                            .needParsed(false)
                            .resultLabelTag(article)
                            .build();

                    parsedLinks.add(itemRecord);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            List<Selectable> all = httpPage.getHtml().xpath("//div[@class=\"prod_yingcai_list\"]/ul/li").nodes();
            for (Selectable node : all) {
                String itemUrl = StringEscapeUtils.unescapeHtml4(node.xpath("./a/@href").get());
                if (StringUtils.isBlank(itemUrl)) {
                    continue;
                }

                itemUrl = itemUrl.matches(articleUrl) ? itemUrl : prefixUrl + itemUrl;

                String releaseTime = node.xpath("./span/text()").get();
                if (StringUtils.isBlank(releaseTime)) {
                    continue;
                }

                if(releaseTime.matches("\\d{6}-\\d{2}")){
                    String[] split = releaseTime.split("-");
                    releaseTime = split[0].substring(0,4) + "-" + split[0].substring(4) + "-" + split[1];
                }
                try {
                    Long releaseTimeToLong = DateUtils.parseDate(releaseTime.trim(), "yyyy-MM-dd").getTime();

                    CrawlerRequestRecord itemRecord = CrawlerRequestRecord.builder()
                            .itemPageRequest(crawlerRequestRecord)
                            .recordKey(itemUrl)
                            .httpUrl(itemUrl)
                            .releaseTime(releaseTimeToLong)
                            .needParsed(false)
                            .resultLabelTag(article)
                            .build();

                    parsedLinks.add(itemRecord);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return parsedLinks;
    }

    @Override
    public List<CrawlerData> washPage(CrawlerRequestRecord crawlerRecord, HttpPage page) {
        List<CrawlerData> crawlerDataList = new ArrayList<>();
        CrawlerResultTags crawlerResultTags = crawlerRecord.tagsCreator().resultTags();
        if (crawlerResultTags.hasDataType(article)) {
            crawlerDataList.add(washArticle(crawlerRecord, page));

        }

        return crawlerDataList;
    }

    public CrawlerData washArticle(CrawlerRequestRecord crawlerRequestRecord, HttpPage httpPage) {

        List<String> articleTextList = httpPage.getHtml().xpath("//div[@class=\"detail_content\"]//p//text()").all();

        StringBuffer conents = new StringBuffer();
        for (String articleText : articleTextList) {
            conents.append(StringEscapeUtils.unescapeHtml4(articleText)).append(" ");
        }

        String itemUrl = httpPage.getRequest().getUrl();
        String articleKey = "";
        if (itemUrl.matches("http://cnsf99.com/\\S*/index.html\\?id=\\d*&aid=\\d*")) {
            articleKey = itemUrl.substring(itemUrl.lastIndexOf("=") + 1);
        } else {
            articleKey = itemUrl.substring(itemUrl.lastIndexOf("/") + 1);
        }

        String authorAndTime = httpPage.getHtml().xpath("//div[@class=\"detail_info\"]/text()").get();
        String author = "";
        if(StringUtils.isNotEmpty(authorAndTime)){
            String[] split = authorAndTime.split("  ");
            for (String s : split) {
                if(s.matches("来源: \\S*")){
                    author = s.substring(s.indexOf(": ") + 1);
                    break;
                }
            }
        }

        String title = httpPage.getHtml().xpath("//div[@class=\"detail_title\"]/text()").get();

        CrawlerData crawlerData = null;

        crawlerData = CrawlerData.builder()
                .data(crawlerRequestRecord, httpPage)
                .dataId(StringUtils.joinWith("-", crawlerRequestRecord.getDomain(), CrawlerEnum.CrawlerDataType.article.enumVal(), articleKey))
                .resultLabelTag(CrawlerEnum.CrawlerDataType.valueOf("article"))
                .url(itemUrl)
                .releaseTime(crawlerRequestRecord.getReleaseTime())
                .addContentKV(Field_Content, conents.toString().trim())
                .addContentKV(Field_Title, StringEscapeUtils.unescapeHtml4(title))
                .addContentKV(Field_Author, author)
                .build();

        return crawlerData;

    }

    @Override
    public void afterExecute(CrawlerRecordContext crawlerRecordContext) {

    }

}
